﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using System.IO;
namespace ABP.AutoCode
{
   public  class CodeService
    {
        /// <summary>
        /// AppDomain服务
        /// </summary>
        public IServiceProvider serviceProvider;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="serviceProvider"></param>
        public CodeService(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
            
        }
        /// <summary>
        /// 输出文件
        /// </summary>
        /// <param name="inputfile">模板文件路径</param>
        /// <param name="outputfile">输出文件路径</param>
        /// <param name="ListParams">参数列表</param>
        public void OutputText(string inputfile,string outputfile,List<KeyValuePair<string,object>> ListParams)
        {
            ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
           

            //https://msdn.microsoft.com/zh-cn/library/gg586947.aspx
            ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;

            // Create a Session in which to pass parameters:  
            sessionHost.Session = sessionHost.CreateSession();
            foreach(KeyValuePair<string,object> param in ListParams){

                sessionHost.Session.Add(param);
            }
            
            
            string result = t4.ProcessTemplate(inputfile, File.ReadAllText(inputfile));

            File.WriteAllText(outputfile, result);


        }
    }
}
